package cn.com.callback

import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean
import cn.com.kh.LogToDB
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @projectName: ngsapitask-sw
 * @className: apiUnicomSMSResult
 * @author: LiJT
 * @description: 联通短信平台发送成功回调API
 * @date: 2022-09-27 00:12
 * @version: 1.0
 */

public class apiUnicomSMSResult implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiUnicomSMSResult.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);
        long startTime = System.currentTimeMillis();

        String inData = "";
        JSONObject outData = new JSONObject();

        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            // 解析短信结果推送
            JSONObject sendResultJson = JSONObject.fromObject(inData);

            // 解析返回信息
            JSONArray reportList = sendResultJson.has("reportList") ? sendResultJson.getJSONArray("reportList") : [];
            int listSize = reportList.size();
            int loopNum = 0;
            List<Object[]> paramListIns = new ArrayList<>();
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
            for (int i = 0; i < listSize; i++) {

                String r_msgId = reportList.getJSONObject(i).getString("msgId");
                String r_status = reportList.getJSONObject(i).getString("status");
                String r_statusDes = reportList.getJSONObject(i).getString("statusDes");
                String r_reportTime = reportList.getJSONObject(i).getString("reportTime");
                log.debug("短信结果推送处理-msgId:" + r_msgId + " status:" + r_status + " statusDes:" + r_statusDes + " reportTime:" + r_reportTime);

                String[] paramArr = new String[4];
                paramArr[0] = r_status;
                paramArr[1] = r_reportTime;
                paramArr[2] = r_statusDes;
                paramArr[3] = r_msgId;
                paramListIns.add(paramArr);

                loopNum++;

                // 如果当前批次已经到100提交一次DB
                if (loopNum >= 200) {

                    log.debug("短信结果推送处理-如果当前批次已经到" + loopNum + "提交一次DB");
                    String batchInsert = '''Update Documentout
                                               Set Result         = ?,
                                                   Resultcount    = Resultcount + 1,
                                                   Finishdatetime = ?,
                                                   Modifiedby     = 'SELITE',
                                                   Modifieddate   = Getdate(),
                                                   Resulttrytime  = Getdate(),
                                                   Comments       = ?
                                             Where Msgid = ?''';
                    jt.batchUpdate(batchInsert, paramListIns);
                    log.debug("短信结果推送处理-如果当前批次已经到" + loopNum + "提交一次DB End");
                    paramListIns.clear();

                    loopNum = 0;
                }

            }

            // 最后批次未达到200提交一次DB
            if (loopNum > 0) {
                log.debug("短信结果推送处理-最后批次达到" + loopNum + "提交一次DB");
                String batchInsert = '''Update Documentout
                                               Set Result         = ?,
                                                   Resultcount    = Resultcount + 1,
                                                   Finishdatetime = ?,
                                                   Modifiedby     = 'SELITE',
                                                   Modifieddate   = Getdate(),
                                                   Resulttrytime  = Getdate(),
                                                   Comments       = ?
                                             Where Msgid = ?''';
                jt.batchUpdate(batchInsert, paramListIns);
                log.debug("短信结果推送处理-最后批次达到" + loopNum + "提交一次DB End");
            }

            // 失败返回
            outData.put("code", "0");
            outData.put("msg", "短信结果推送处理-处理完成,总条数:" + listSize);

        } catch (Exception e) {
            log.error("短信结果推送处理-接口处理异常" + e.getMessage());
            // 失败返回
            outData.put("code", "-1");
            outData.put("msg", e.getMessage());
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "短信平台发送结果推送[普通]", "apiUnicomSMSResult", inData, outData.toString(), (System.currentTimeMillis() - startTime).toString(), "/");
        }

        log.debug("短信结果推送处理-处理完成返回结果:" + outData.toString());

        return outData.toString();
    }
}